全稱:快速響應矩陣條碼,是二維條碼的一種,一般為黑白兩色且三個角落有回字形的定位圖案,用來確保資料被正確讀取
在開始之前,我們必須先取得相機權限,到 Info.plist ,按 Information Property List 旁邊的加號
新增 Privacy - Camera Usage Description
並填入給使用者的提示訊息
並建立相機的預覽畫面
輸入以下程式碼
import UIKit
import AVFoundation
class ViewController: UIViewController {
@IBOutlet weak var qrcodeView: UIView!
var captureSesion: AVCaptureSession?
var previewLayer: AVCaptureVideoPreviewLayer!
var QRCodeString: String!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
captureSesion?.startRunning()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
setQRCodeScan()
}
func setQRCodeScan() {
// 實體化AVCaptureSession物件
captureSesion = AVCaptureSession()
guard let videoCaptureDevice = AVCaptureDevice.default(for: .video) else { return }
let videoInput: AVCaptureDeviceInput
do {
videoInput = try AVCaptureDeviceInput(device: videoCaptureDevice)
} catch let error {
print(error)
return
}
if (captureSesion?.canAddInput(videoInput) ?? false ) {
captureSesion?.addInput(videoInput)
} else { return }
// 實體化AVCaptureMetaDataOutput物件,用來輸出影音資料
let metaDataOutput = AVCaptureMetadataOutput()
if (captureSesion?.canAddOutput(metaDataOutput) ?? false) {
captureSesion?.addOutput(metaDataOutput)
// 執行緒處理QRCode
metaDataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
// metadataObjectTypes表示要處理的資料類型,處理QRCODE
metaDataOutput.metadataObjectTypes = [.qr]
} else { return }
// 用PreviewLayer來顯示Session上的資料
previewLayer = AVCaptureVideoPreviewLayer(session: captureSesion!)
// 顯示方式
previewLayer.videoGravity = .resizeAspectFill
// 呈現在qrcodeView上面
previewLayer.frame = qrcodeView.layer.frame
// 加入畫面
view.layer.addSublayer(previewLayer)
// 開始影像擷取呈現鏡頭的畫面
captureSesion?.startRunning()
}
}
extension ViewController: AVCaptureMetadataOutputObjectsDelegate {
func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
captureSesion?.startRunning()
// 有讀取到資料
if let metadataObject = metadataObjects.first{
guard let readableObject = metadataObject as? AVMetadataMachineReadableCodeObject else {return}
// 將讀取到的內容轉成string
guard let stringValue = readableObject.stringValue else {return}
// 將string資料print出來
print(stringValue)
// 存取QRcode資料
QRCodeString = stringValue
let alert = UIAlertController(title: "提示", message: QRCodeString, preferredStyle: .alert)
let action = UIAlertAction(title: "確認", style: .default) { (action) in
// 確認後繼續掃描工作
self.captureSesion?.startRunning()
}
alert.addAction(action)
self.present(alert, animated: true) {
// 在使用者確認內容之前先暫停掃描
self.captureSesion?.stopRunning()
}
}
}
}
第一次執行時會跳出提示,要求相機權限
接著就能正常掃描 QR Code 啦!
這邊放個讓大家測試!